//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.goldhuman.Common;

import java.util.*;

public class TimerTask implements Observer {
    private static TimerTask instance = new TimerTask();
    private static SortedMap<Long, LinkedList<TaskPair>> tasks = Collections.synchronizedSortedMap(new TreeMap());
    private long elapse = 0L;

    private TimerTask() {
        TimerObserver.GetInstance().addObserver(this);
    }

    public synchronized void update(Observable o, Object arg) {
        ++this.elapse;
        synchronized(tasks) {
            Set<Map.Entry<Long, LinkedList<TaskPair>>> entryset = tasks.entrySet();
            Iterator<Map.Entry<Long, LinkedList<TaskPair>>> it = entryset.iterator();

            while(it.hasNext()) {
                Map.Entry<Long, LinkedList<TaskPair>> map_entry = (Map.Entry)it.next();
                LinkedList<TaskPair> ll = (LinkedList)map_entry.getValue();
                Iterator<TaskPair> iter = ll.iterator();
                synchronized(ll) {
                    while(iter.hasNext()) {
                        TaskPair tp = (TaskPair)iter.next();
                        if (tp.waitsecds > this.elapse) {
                            break;
                        }

                        ThreadPool.AddTask(tp.task);
                        iter.remove();
                    }
                }

                if (ll.isEmpty()) {
                    it.remove();
                }
            }

        }
    }

    public synchronized void AddTask(com.goldhuman.Common.Runnable task, long waitsecds) {
        LinkedList<TaskPair> ll = (LinkedList)tasks.get(waitsecds);
        if (ll == null) {
            tasks.put(waitsecds, ll = new LinkedList());
        }

        synchronized(ll) {
            ll.addFirst(new TaskPair(waitsecds + this.elapse, task));
        }
    }

    public static void AddTimerTask(com.goldhuman.Common.Runnable task, long waitsecds) {
        instance.AddTask(task, waitsecds);
    }

    private class TaskPair {
        long waitsecds;
        com.goldhuman.Common.Runnable task;

        TaskPair(long _w, Runnable _t) {
            this.waitsecds = _w;
            this.task = _t;
        }
    }
}
